package com.atguigu.reentrantLock;

import java.util.concurrent.locks.ReentrantLock;

//使用ReentrantLock锁改造买票程序
class Ticket{
    private final ReentrantLock lock = new ReentrantLock();
    //定义一个票数
    private int number = 100;

    //定义一个买票的方法
    public void sale(){
        //上锁
        lock.lock();
        if(number<=0){
            System.out.println(Thread.currentThread().getName()+"票已经卖完了");
            lock.unlock();
            System.out.println("return");
            return;
        }
        //卖票
        System.out.println(Thread.currentThread().getName()+"卖出了第"+(number--)+"票"+"还剩"+number+"张");
        lock.unlock();

    }


        }
public class SaleTicket2 {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    ticket.sale();
                }
            }
        },"A").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    ticket.sale();
                }
            }
        },"B").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    ticket.sale();
                }
            }
        },"C").start();
    }
}
